package com.hl.card.modular.packBack.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.hl.card.common.persistence.dao.CreditCardLogMapper;
import com.hl.card.common.persistence.dao.CreditCardMapper;
import com.hl.card.common.persistence.dao.UserMapper;
import com.hl.card.common.persistence.model.CreditCard;
import com.hl.card.common.persistence.model.CreditCardLog;
import com.hl.card.common.persistence.model.User;
import com.hl.card.common.util.DateUtils;
import com.hl.card.common.util.RadomUtil;
import com.hl.card.core.shiro.ShiroKit;
import com.hl.card.modular.packBack.service.CreditCardService;
import com.hl.card.mq.Mq4NotifyDemo;
import com.hl.card.mq.MqCustomConfig;

/**
 * 交通银行信用卡业务逻辑处理层
 * 
 * @author 袁伟
 *
 */
@Service
public class CreditCardServiceImpl implements CreditCardService {
	@Autowired
	private CreditCardMapper creditCardMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private CreditCardLogMapper creditCardLogMapper;
	@Autowired
	private Mq4NotifyDemo mq4NotifyDemo;
	/**
	 * 导入excel表格
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public Map<String,Object> uploadExcel(List<CreditCard> dataList,HttpServletRequest request) {
		int total_count=dataList.size();
		int success_count=0;
		int error_count=0;
		int update_count=0;
		Map<String,Object> result=new HashMap<String, Object>();
	    Integer id = ShiroKit.getUser().getId();
		Date time = DateUtils.getNow();
		for (int i = 0; i < dataList.size(); i++) {
			CreditCard data = dataList.get(i);
			request.getSession().setAttribute("upload_count" + id, i+1);
			if(StringUtils.isEmpty(data.getPhone()))
			{
				CreditCardLog log=new CreditCardLog();
				log.setPhone("空白号码");
				log.setRemark("手机号码为空");
				creditCardLogMapper.add(log);
				error_count++;
				continue;
			}
			String phone= data.getPhone();
			String param[] = phone.split("[****]{4}");
			if (param.length == 1) // 精确查询
			{
				List<User> userList=userMapper.searchCardByNo(data.getPhone());
				if(userList==null||userList.size()==0)     
				{
					CreditCardLog log=new CreditCardLog();
					log.setPhone(data.getPhone());
					log.setRemark("非比比旅行用户");
					creditCardLogMapper.add(log);
					error_count++;
				}else if (userList.size() == 1) 
				{
					List<CreditCard> list = creditCardMapper.searchCardByNo(data.getPhone());
					if (list == null || list.size() == 0) {
						data.setPhone(userList.get(0).getPhone());   //设置帐号为匹配上的帐号
						data.setCustomer_name(userList.get(0).getName());
						data.setCreate_time(time);
						data.setUpdate_time(time);
						data.setCard_no(createCode());
						returnStatus(data);
						creditCardMapper.add(data);
						reward(data,userList.get(0).getUserId());  
						success_count++;
						// 添加
					} else if (list.size() == 1) {
						CreditCard card = list.get(0);
						if(!card.equals(data))
						{
							Integer status=card.getStatus();
							card.setUpdate_time(time);
							card.setCustomer_name(userList.get(0).getName());
							card.setActivation_time(data.getActivation_time());
							card.setApply_no(data.getApply_no());
							card.setCard_level(data.getCard_level());
							card.setCard_product(data.getCard_product());
							card.setCard_status(data.getCard_status());
							card.setConsume_time(data.getConsume_time());
							card.setCustomer_status(data.getCustomer_status());
							card.setExamine_time(data.getExamine_time());
							card.setIs_active(data.getIs_active());
							card.setIs_new(data.getIs_new());
							card.setLive_consume_time(data.getLive_consume_time());
							card.setTrack_code(data.getTrack_code());
							card.setAdd_time(data.getAdd_time());
							returnStatus(card);
							creditCardMapper.update(card);
							if(!card.getStatus().equals(status))
							{
							 	reward(card,userList.get(0).getUserId()); 
							}
							update_count++;
						}
						// 更新
						success_count++;
					
					} else {
						// 重复提示
						CreditCardLog log=new CreditCardLog();
						log.setPhone(data.getPhone());
						log.setRemark("在信用卡记录内有重复号码");
						creditCardLogMapper.add(log);
						error_count++;
					}

				} else 
				{
					String name=data.getCustomer_name().replace("*","%");
					Map<String,Object> map=new HashMap<String, Object>();
					map.put("phone", data.getPhone());
					map.put("param3", name);
					List<User> uList=userMapper.searchCardByNoAndName(map);
					if(uList==null||uList.size()==0)
					{
						CreditCardLog log=new CreditCardLog();
						log.setPhone(data.getPhone());
						log.setRemark("客户姓名与比比旅行姓名不匹配");
						creditCardLogMapper.add(log);
						error_count++;
					}else if(uList.size()==1)   //如果加姓名联合匹配到只有一个
					{
						List<CreditCard> list = creditCardMapper.searchCardByNo(uList.get(0).getPhone());
						if (list == null || list.size() == 0) {
							data.setPhone(userList.get(0).getPhone());   //设置帐号为匹配上的帐号
							data.setCustomer_name(userList.get(0).getName());
							data.setCreate_time(time);
							data.setUpdate_time(time);
							data.setCard_no(createCode());
							returnStatus(data);
							creditCardMapper.add(data);
							reward(data,userList.get(0).getUserId()); 
							success_count++;
							// 添加
						} else if (list.size() == 1) {
							CreditCard card = list.get(0);
							if(!card.equals(data))
							{
							Integer status=card.getStatus();
							card.setCustomer_name(userList.get(0).getName());
							card.setUpdate_time(time);
							card.setActivation_time(data.getActivation_time());
							card.setApply_no(data.getApply_no());
							card.setCard_level(data.getCard_level());
							card.setCard_product(data.getCard_product());
							card.setCard_status(data.getCard_status());
							card.setConsume_time(data.getConsume_time());
							card.setCustomer_status(data.getCustomer_status());
							card.setExamine_time(data.getExamine_time());
							card.setIs_active(data.getIs_active());
							card.setIs_new(data.getIs_new());
							card.setLive_consume_time(data.getLive_consume_time());
							card.setTrack_code(data.getTrack_code());
							card.setAdd_time(data.getAdd_time());
							returnStatus(card);
							creditCardMapper.update(card);
							if(!card.getStatus().equals(status))
							{
							 	reward(card,userList.get(0).getUserId()); 
							}
							update_count++;
							}
							// 更新
							success_count++;
							
						} else {
							// 重复提示
							CreditCardLog log=new CreditCardLog();
							log.setPhone(data.getPhone());
							log.setRemark("在信用卡记录内有重复号码");
							creditCardLogMapper.add(log);
							error_count++;
						}
						
					}else
					{
						CreditCardLog log=new CreditCardLog();
						log.setPhone(data.getPhone());
						log.setRemark("在比比旅行内有重复号码");
						creditCardLogMapper.add(log);
						error_count++;
					}
				
				}
			}else
			{
				String name=data.getCustomer_name().replace("*","%");
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("param1", param[0]);
				map.put("param2", param[1]);
				List<User> userList=userMapper.searchCardByNoRegexp(map);
				if(userList==null||userList.size()==0)
				{
					CreditCardLog log=new CreditCardLog();
					log.setPhone(data.getPhone());
					log.setRemark("非比比旅行用户");
					creditCardLogMapper.add(log);
					error_count++;
				}else if (userList.size() == 1)
				{
					List<CreditCard> list = creditCardMapper.searchCardByNoRegexp(map);
					if (list == null || list.size() == 0) {
						data.setPhone(userList.get(0).getPhone());   //设置帐号为匹配上的帐号
						data.setCustomer_name(userList.get(0).getName());
						data.setCreate_time(time);
						data.setUpdate_time(time);
						data.setCard_no(createCode());
						returnStatus(data);
						creditCardMapper.add(data);
					 	reward(data,userList.get(0).getUserId()); 
						success_count++;
						// 添加
					} else if (list.size() == 1) {
						CreditCard card = list.get(0);
						if(!card.equals(data))
						{
					    Integer status=card.getStatus();
						card.setCustomer_name(userList.get(0).getName());
						card.setUpdate_time(time);
						card.setActivation_time(data.getActivation_time());
						card.setApply_no(data.getApply_no());
						card.setCard_level(data.getCard_level());
						card.setCard_product(data.getCard_product());
						card.setCard_status(data.getCard_status());
						card.setConsume_time(data.getConsume_time());
						card.setCustomer_status(data.getCustomer_status());
						card.setExamine_time(data.getExamine_time());
						card.setIs_active(data.getIs_active());
						card.setIs_new(data.getIs_new());
						card.setLive_consume_time(data.getLive_consume_time());
						card.setTrack_code(data.getTrack_code());
						card.setAdd_time(data.getAdd_time());
						returnStatus(card);
						creditCardMapper.update(card);
						if(!card.getStatus().equals(status))
						{
						 	reward(card,userList.get(0).getUserId()); 
						}
						update_count++;
						}
						success_count++;
						
						// 更新
	                
					} else {
						// 重复提示
						CreditCardLog log=new CreditCardLog();
						log.setPhone(data.getPhone());
						log.setRemark("在信用卡记录内有重复号码");
						creditCardLogMapper.add(log);
						error_count++;
					}
				}else
				{
					map.put("param3", name);
					List<User> uList=userMapper.searchCardByNoAndNameRegexp(map);
					if(uList==null||uList.size()==0)
					{
						CreditCardLog log=new CreditCardLog();
						log.setPhone(data.getPhone());
						log.setRemark("客户姓名与比比旅行姓名不匹配");
						creditCardLogMapper.add(log);
						error_count++;
					}else if(uList.size()==1)
					{
						List<CreditCard> list = creditCardMapper.searchCardByNo(uList.get(0).getPhone());
						if (list == null || list.size() == 0) {
							data.setCustomer_name(uList.get(0).getName());
							data.setPhone(uList.get(0).getPhone());   //设置帐号为匹配上的帐号
							data.setCreate_time(time);
							data.setUpdate_time(time);
							data.setCard_no(createCode());
							returnStatus(data);
							creditCardMapper.add(data);
						 	reward(data,uList.get(0).getUserId()); 
							success_count++;
							// 添加
						} else if (list.size() == 1) {
							CreditCard card = list.get(0);
							if(!card.equals(data))
							{
							Integer status=card.getStatus();
							card.setCustomer_name(uList.get(0).getName());
							card.setPhone(uList.get(0).getPhone());
							card.setUpdate_time(time);
							card.setActivation_time(data.getActivation_time());
							card.setApply_no(data.getApply_no());
							card.setCard_level(data.getCard_level());
							card.setCard_product(data.getCard_product());
							card.setCard_status(data.getCard_status());
							card.setConsume_time(data.getConsume_time());
							card.setCustomer_status(data.getCustomer_status());
							card.setExamine_time(data.getExamine_time());
							card.setIs_active(data.getIs_active());
							card.setIs_new(data.getIs_new());
							card.setLive_consume_time(data.getLive_consume_time());
							card.setTrack_code(data.getTrack_code());
							card.setAdd_time(data.getAdd_time());
							returnStatus(card);
							creditCardMapper.update(card);
							if(!card.getStatus().equals(status))
							{
							 	reward(card,uList.get(0).getUserId()); 
							}
							update_count++;
							}
							success_count++;
							
							// 更新
		                
						} else {
							// 重复提示
							CreditCardLog log=new CreditCardLog();
							log.setPhone(data.getPhone());
							log.setRemark("在信用卡记录内有重复号码");
							creditCardLogMapper.add(log);
							error_count++;
						}
					}else
					{
						CreditCardLog log=new CreditCardLog();
						log.setPhone(data.getPhone());
						log.setRemark("在比比旅行内有重复号码");
						creditCardLogMapper.add(log);
						error_count++;
					}
					
					
				
				}
				
			
			}
			
		}
		result.put("update_count", update_count);
		result.put("total_count", total_count);
		result.put("success_count", success_count);
		result.put("error_count", error_count);
		return result;
	}
	
	public void returnStatus(CreditCard card)
	{
		if(card.getCard_status().equals(0)&&card.getCustomer_status().equals(1)&&card.getAdd_time()!=null&&card.getExamine_time()==null)
		{
			card.setStatus(0);
		}else if(card.getCard_status().equals(0)&&card.getExamine_time()!=null&&card.getCustomer_status().equals(1))
		{
			card.setStatus(1);	
		}else if(card.getCard_status().equals(1)&&card.getActivation_time()!=null)
		{
			card.setStatus(2);	
		}else if(card.getCustomer_status().equals(0)&&card.getExamine_time()==null)
		{
			card.setStatus(3);	
		}
	}
	
	public void reward(CreditCard card,String user_id)
	{
		if(card.getStatus().equals(1)&&card.getIs_new().equals(1))   //是新户并且待激活发未到账奖励
		{
			JSONObject map = new JSONObject();
			map.put("function", "makeAwardManualUnfreeze");
			map.put("parentCode", "JTC");
			map.put("userId", user_id);
			map.put("amount", "360");
			map.put("unfreezeTime", "manual");
			map.put("orderId", card.getCard_no());
			map.put("queueName", MqCustomConfig.QUEUE_AWARD_ADMIN_CARD); 
			mq4NotifyDemo.send(MqCustomConfig.QUEUE_AWARD,map.toJSONString());
		}
		if(card.getStatus().equals(2)&&card.getIs_new().equals(1))   //是新户并且已激活发奖励
		{
			String remark= card.getReward_remark();
			if(!StringUtils.isEmpty(remark))
			{
				JSONObject obj=JSONObject.parseObject(remark);
				if(obj.get("erroCode").equals(0))   //成功标识
				{
				    JSONObject data=obj.getJSONObject("data");
				    String  communityAdminUserId= data.getString("communityAdminUserId");
				    String  recommenderUserId=data.getString("recommenderUserId");
				    String  selfUserId=data.getString("selfUserId");
					if(!StringUtils.isEmpty(communityAdminUserId))
					{
						Map<String, String> map = new HashMap<String, String>();
						map.put("unfreeze", "manual");
			            map.put("userId", communityAdminUserId);
			            map.put("mchOrderNo", card.getCard_no());
			            map.put("amount", data.get("communityAdmin").toString());
			            map.put("isFree", "isFree");
						mq4NotifyDemo.send("queue.notify.mch.unfreeze",map.toString());
					}
					if(!StringUtils.isEmpty(recommenderUserId))
					{
						Map<String, String> map = new HashMap<String, String>();
						map.put("unfreeze", "manual");
			            map.put("userId", recommenderUserId);
			            map.put("mchOrderNo", card.getCard_no());
			            map.put("amount",data.get("recommender").toString());
			            map.put("isFree", "isFree");
						mq4NotifyDemo.send("queue.notify.mch.unfreeze",map.toString());
					}
					if(!StringUtils.isEmpty(selfUserId))
					{
						Map<String, String> map = new HashMap<String, String>();
						map.put("unfreeze", "manual");
			            map.put("userId", selfUserId);
			            map.put("mchOrderNo", card.getCard_no());
			            map.put("amount", data.get("userId").toString());
			            map.put("isFree", "isFree");
						mq4NotifyDemo.send("queue.notify.mch.unfreeze",map.toString());
					}
				}
				
			}else
			{
				JSONObject map = new JSONObject();
				map.put("function", "makeAward");
				map.put("parentCode", "JTC");
				map.put("userId", user_id);
				map.put("amount", "360");
				map.put("orderId", card.getCard_no());
				map.put("queueName", MqCustomConfig.QUEUE_AWARD_ADMIN_CARD);
				mq4NotifyDemo.send(MqCustomConfig.QUEUE_AWARD,map.toJSONString());
			}
		
		}
	}
   	public String createCode() {
   		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		int a = (int) (Math.random() * 900) + 100;
		String orderNo = format.format(new Date()) + a;
		return "C" + orderNo;
	}
	@Override
	public List<CreditCard> list(Page<CreditCard> page, CreditCard card,
			String sort, String order) {
		int skip = (page.getCurrent() - 1) * page.getSize();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("offset", skip);
		map.put("size", page.getSize());
		if (!StringUtils.isEmpty(sort)) {
			map.put("orderFiled", "order by " + sort + " " + order);
		}
		if (!StringUtils.isEmpty(card.getPhone())) {
			map.put("phone", card.getPhone());
		}
		if (!StringUtils.isEmpty(card.getCustomer_name())) {
			map.put("customer_name", card.getCustomer_name());
		}
		if(card.getStatus()!=null)
		{
			map.put("status", card.getStatus());
		}
		if(card.getCard_status()!=null)
		{
			map.put("card_status", card.getCard_status());
		}
		if(!StringUtils.isEmpty(card.getRefer_reg_code()))
		{
			map.put("refer_reg_code", card.getRefer_reg_code());
		}
		if(!StringUtils.isEmpty(card.getStart_time())&&!StringUtils.isEmpty(card.getEnd_time()))
		{
			
			map.put("start_time", card.getStart_time()+" 00:00:00");
			map.put("end_time", card.getEnd_time()+" 59:59:59");
		}
		page.setTotal(creditCardMapper.listCount(map));
		return creditCardMapper.list(map);
	}

}
